package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.EditBloodInfoBean
import com.gexiaobao.pigeon.app.model.bean.LivePerformanceResponse
import com.gexiaobao.pigeon.app.model.bean.PassResultBody
import com.gexiaobao.pigeon.app.model.bean.RaceDetailInfoResponse
import com.gexiaobao.pigeon.app.util.CycleSender
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentLivePerformanceBinding
import com.gexiaobao.pigeon.ui.activity.ActivityGameResult
import com.gexiaobao.pigeon.ui.adapter.AdapterLivePerformance
import com.gexiaobao.pigeon.ui.adapter.AdapterLivePerformanceXf
import com.gexiaobao.pigeon.ui.adapter.MyAdapter
import com.gexiaobao.pigeon.ui.breeding_pigeon.ActivityMakeBlood
import com.gexiaobao.pigeon.ui.dialog.RxDialogGradleLive
import com.gexiaobao.pigeon.ui.dialog.RxDialogPageTurning
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityPigeonGatheringDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.video.ActivityPlayBack
import com.gexiaobao.pigeon.viewmodel.DialogViewModel
import com.gexiaobao.pigeon.viewmodel.OrgRaceViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import java.text.DecimalFormat
import java.util.Date
import kotlin.math.ceil

/**
 * @Author      : hxw
 * @Date        : 2024/7/17 13:39
 * @Describe    : 成绩直播
 */
class FragmentLivePerformance : BaseFragment<OrgRaceViewModel, FragmentLivePerformanceBinding>() {

    private val mAdapter: AdapterLivePerformance by lazy { AdapterLivePerformance(arrayListOf()) }
    private val mAdapterXf: AdapterLivePerformanceXf by lazy { AdapterLivePerformanceXf(arrayListOf()) }//训放
    private var mPassId = 0
    private var mPageNo = 1
    private var mPageTotal = 0
    private var sortType = "1"//1-升序 2-降序

    //获取当前时间String
    private var currentStr = ""
    private var sunTimeList: ArrayList<String> = arrayListOf()

    //获取当前时间date
    private lateinit var curDate: Date
    private var nightHoursCount: Long = 0
    private var nightTimeCount = 0
    private var flyDistance: Double = 0.0
    private var flyTime = ""

    private var isReverse = true//标记是否是降序还是升序 true-升序，false-降序
    private var mIsPressedSort = false//是否点击了排序按钮
    private var memberCode = ""
    private var mRingId = ""
    private var mFosterName = ""
    private var qStr = ""
    private var title = ""
    private var ringIdTitle = ""
    private var isMember = false
    private var mPassType = 0//1-比赛，
    private var mRaceId = 0

    private var listPopupWindow: ListPopupWindow? = null
    private val mList: MutableList<String> = mutableListOf()
    private var mSearchType = ""
    private var mPassCreateType = 0

    private val sharedViewModel: SharedViewModel by activityViewModels()

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        mSearchType = getString(R.string.search_by_member)
        mDatabind.includeBottomPage.ivLandscape.isVisible = true
        mPassId = requireArguments().getInt("passId", 0)
        title = requireArguments().getString("title").toString()
        mPassType = requireArguments().getInt("passType")
        mPassCreateType = requireArguments().getInt("passCreateType")
        mDatabind.includeSearch.editQuery.hint = getString(R.string.Enter_what_you_want_to_query)
        mDatabind.includeSearch.tvSearchType.textSize = 14F
        mDatabind.includeSearch.ivSearch.isVisible = false
        mDatabind.includeSearch.tvSearchType.text = mSearchType
        mDatabind.tvGatherCount.paint.flags = Paint.UNDERLINE_TEXT_FLAG//设置下划线

        mRaceId = requireArguments().getInt("raceId")

        showLoading(getString(R.string.loading))
        mViewModel.getLiveStreamingData(50, mPageNo, mPassId.toString(), mRaceId.toString(), sortType, memberCode, mRingId, mFosterName, qStr)

        mDatabind.llRaceTitle.isVisible = mPassType == 1
        mDatabind.llControlTitle.isVisible = mPassType != 1

        initPopup()

        if (mPassType == 1) {
            mDatabind.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter)
        } else {
            mDatabind.swipeRecyclerView.init(LinearLayoutManager(context), mAdapterXf)
        }

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.swipeRefreshLayout.init {
            onRefresh(isRefresh = false, isPressedSort = false)
            mViewModel.getPassDetailApp(mPassId.toString())
            mViewModel.getVisitMemberNoList(mRaceId.toString())
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    searchResult()
                }

                else -> {}
            }
            false
        }
        hideSoftKeyboard(activity)

        mAdapter.addChildClickViewIds(R.id.tvItemLiveUserName, R.id.ivItemLiveVideo, R.id.tvSpeed)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvSpeed -> showDetailDialog(mAdapter.data[position])
                R.id.ivItemLiveVideo -> {
                    if (isMember) {
                        startActivity<ActivityPlayBack>(
                            "ringId" to mAdapter.data[position].ringId,
                            "passId" to mPassId,
                            "title" to getString(R.string.back_video),
                            "type" to 2
                        )
                    } else {
                        showMessage(getString(R.string.no_member_and_can_not_look_home_video))
                    }
                }

                R.id.tvItemLiveUserName -> {
                    mRingId = ""
                    mPageNo = 1
                    mDatabind.includeBottomPage.tvPageNumber.text = "1"
                    mFosterName = mAdapter.data[position].username
                    mDatabind.includeSearch.editQuery.setText(mFosterName)
                    onRefresh(isRefresh = true, isPressedSort = false)
                }
            }
        }

        mAdapterXf.addChildClickViewIds(R.id.tvItemLiveUserName, R.id.ivItemLiveVideo, R.id.tvItemRingId)
        mAdapterXf.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvItemRingId -> showDetailDialog(mAdapterXf.data[position])
                R.id.ivItemLiveVideo -> {
                    if (isMember) {
                        startActivity<ActivityPlayBack>(
                            "ringId" to mAdapterXf.data[position].ringId,
                            "passId" to mPassId,
                            "title" to getString(R.string.back_video),
                            "type" to 2
                        )
                    } else {
                        showMessage(getString(R.string.no_member_and_can_not_look_home_video))
                    }
                }

                R.id.tvItemLiveUserName -> {
                    mPageNo = 1
                    mRingId = ""
                    mDatabind.includeBottomPage.tvPageNumber.text = "1"
                    mFosterName = mAdapterXf.data[position].username
                    mDatabind.includeSearch.editQuery.setText(mFosterName)
                    onRefresh(isRefresh = true, isPressedSort = false)
                }
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            showDetailDialog(mAdapter.data[position])
        }

        mAdapterXf.setOnItemClickListener { _, _, position ->
            showDetailDialog(mAdapterXf.data[position])
        }

        listPopupWindow?.setOnItemClickListener { _, _, position, _ ->
            mSearchType = mList[position]
            mDatabind.includeSearch.tvSearchType.text = mSearchType
            mList.add(0, mList.removeAt(position))
            listPopupWindow!!.dismiss()
        }

        sharedViewModel.data.observe(viewLifecycleOwner) {
            if (it != null) {
                title = it.titleName
                mPassId = it.id
                onRefresh(isRefresh = false, isPressedSort = false)
                mViewModel.getPassDetailApp(mPassId.toString())
            }
        }
    }

    private fun initPopup() {
        mList.add(getString(R.string.search_by_member))
        mList.add(getString(R.string.search_by_ringId))
        /** 初始化ListPopupWindow，适配 */
        listPopupWindow = ListPopupWindow(requireContext())
        val adapter = MyAdapter(requireContext(), mList)
        listPopupWindow?.setAdapter(adapter)
        listPopupWindow?.anchorView = mDatabind.includeSearch.llSearchType//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow?.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.isModal = true
    }

    private fun showDetailDialog(data: PassResultBody) {
        ringIdTitle = data.ringId
        val viewModel: DialogViewModel = ViewModelProvider(this)[DialogViewModel::class.java]
        viewModel.setData(data)
        val dialog = RxDialogGradleLive(context, viewModel)
        dialog.setSureListener {
            intentToGameResult()
            dialog.dismiss()
        }
        val videoStatus = if (data.operation == null) {
            false
        } else {
            data.operation.videoStatus == 2
        }
        val picStatus = if (data.operation == null) {
            false
        } else {
            data.operation.picStatus == 2
        }
        dialog.setHideVideo(videoStatus)
        dialog.setHidePicture(picStatus)
        dialog.setHideBlood(mPassCreateType == 1)
        dialog.setHomingVideoListener {
            dialog.dismiss()
            if (isMember) {
                startActivity<ActivityPlayBack>("ringId" to data.ringId, "passId" to mPassId, "title" to getString(R.string.back_video), "type" to 2)
            } else {
                showMessage(getString(R.string.no_member_and_can_not_look_home_video))
            }
        }
        dialog.setHomingPictureListener {

        }
        dialog.setToBloodListener {
            val editBloodInfo = EditBloodInfoBean(
                country = "",
                countryEn = "",
                eye = "",
                featherColor = "",
                gradesDesc = "",
                level = 1,
                levelInfo = "1",
                name = "",
                ringId = data.ringId,
                sex = "",
                title = getString(R.string.Chief_pigeon),
            )
            startActivity<ActivityMakeBlood>(
                "type" to "grade",
                "pigeonId" to data.operation.pigeonId,
                "ringId" to data.ringId,
                "memberId" to data.operation.memberId,
                "editBloodInfo" to editBloodInfo,
            )
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun intentToGameResult() {
        startActivity<ActivityGameResult>("title" to title, "passId" to mPassId, "type" to "race", "raceId" to mRaceId)
    }

    private fun searchResult() {
        mPageNo = 1
        mDatabind.includeBottomPage.tvPageNumber.text = "1"
        hideSoftKeyboard(activity)
        if (mSearchType == getString(R.string.search_by_member)) {
            mFosterName = mDatabind.includeSearch.editQuery.text.toString().trim()
            mRingId = ""
        } else {
            mRingId = mDatabind.includeSearch.editQuery.text.toString().trim()
            mFosterName = ""
        }
        onRefresh(isRefresh = true, isPressedSort = false)
    }

    private fun onRefresh(isRefresh: Boolean, isPressedSort: Boolean) {
        mIsPressedSort = isPressedSort
        if (mIsPressedSort) {
            sortType = if (isReverse) {
                "2"
            } else {
                "1"
            }
        }
        if (isRefresh) {
            showLoading(getString(R.string.loading))
        }
//        mViewModel.getOrgPassResult(isRefresh, 50, mPageNo, mPassId.toString(), sortType, memberCode, mRingId, mFosterName, qStr)
        mViewModel.getLiveStreamingData(50, mPageNo, mPassId.toString(), mRaceId.toString(), sortType, memberCode, mRingId, mFosterName, qStr)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.constrainLayout,
            mDatabind.includeSearch.ivClose,
            mDatabind.llAscendingOrder,
            mDatabind.includeBottomPage.ivLandscape,
            mDatabind.includeSearch.tvSearch,
            mDatabind.includeSearch.llSearchType,
            mDatabind.llAllData,
            mDatabind.llGatherCount,
            mDatabind.includeBottomPage.tvThrough,
            mDatabind.includeBottomPage.tvFirstPage,
            mDatabind.includeBottomPage.tvLastPage,
            mDatabind.includeBottomPage.tvPageUp,
            mDatabind.includeBottomPage.tvNextPage
        ) {
            when (it) {
                mDatabind.includeBottomPage.tvNextPage -> {
                    if (mPageNo == mPageTotal) {
                        RxToast.warning(getString(R.string.last_page))
                        return@setOnclickNoRepeat
                    }
                    mPageNo++
                    onRefresh(isRefresh = true, isPressedSort = false)
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvPageUp -> {
                    if (mPageNo == 1) {
                        RxToast.warning(getString(R.string.first_page))
                        return@setOnclickNoRepeat
                    }
                    mPageNo--
                    onRefresh(isRefresh = true, isPressedSort = false)
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvLastPage -> {
                    mPageNo = mPageTotal
                    onRefresh(isRefresh = true, isPressedSort = false)
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvFirstPage -> {
                    mPageNo = 1
                    onRefresh(isRefresh = true, isPressedSort = false)
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvThrough -> showDialogPageTurning()
                mDatabind.llGatherCount -> startActivity<ActivityPigeonGatheringDetail>(
                    "passId" to mPassId,
                    "title" to title,
                    "memberCode" to "",//可不传，暂时弃用
                    "raceId" to mRaceId
                )

                mDatabind.llAllData -> {
                    mFosterName = ""
                    mRingId = ""
                    mDatabind.includeSearch.editQuery.setText("")
                    onRefresh(isRefresh = true, isPressedSort = false)
                }

                mDatabind.includeSearch.llSearchType -> listPopupWindow?.show()
                mDatabind.includeSearch.tvSearch -> searchResult()
                mDatabind.includeBottomPage.ivLandscape -> intentToGameResult()
                mDatabind.llAscendingOrder -> {
                    onRefresh(isRefresh = true, isPressedSort = true)
                }

                mDatabind.includeSearch.ivClose -> {
                    mDatabind.includeSearch.editQuery.setText("")
                    mFosterName = ""
                    mRingId = ""
                    onRefresh(isRefresh = true, isPressedSort = false)
                }

                mDatabind.constrainLayout -> {

                }
            }
        }
    }

    private fun showDialogPageTurning() {
        var pageNumber: Int
        val dialog = RxDialogPageTurning(context)
        dialog.setTitle(getString(R.string.chose_look_page) + "\n" + getString(R.string.altogether) + mPageTotal + getString(R.string.page))
        dialog.setPlusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (pageNumber > mPageTotal) {
                RxToast.warning(getString(R.string.has_exceeded_the_total_page))
                return@setPlusListener
            }
            if (pageNumber == mPageTotal) {
                RxToast.warning(getString(R.string.last_page))
                return@setPlusListener
            }
            pageNumber++
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setMinusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }

            if (pageNumber == 1) {
                RxToast.warning(getString(R.string.first_page))
                return@setMinusListener
            }
            pageNumber--
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setSureListener {
            mPageNo = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (mPageNo > mPageTotal) {
                RxToast.warning(getString(R.string.has_exceeded_the_total_page))
                return@setSureListener
            }
            mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
            onRefresh(isRefresh = false, isPressedSort = false)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }


    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        /** 获取单用户下探视棚号列表  */
        mViewModel.visitMemberResult.observe(this) {
            dismissLoading()
            isMember = it.list.isNotEmpty()
        }
        /**  比赛详细信息  */
        mViewModel.detailInfoResult.observe(viewLifecycleOwner) {
            if (it != null) {
                flyTime = it.flyTime
                flyDistance = it.flyDis.toDouble()
                mDatabind.tvValidSpeed.text = getString(R.string.valid_speed) + ": " + it.effSpeed.toString() + getString(R.string.Meter_minute)
                if (it.passStatus == 6) {
                    getCalculateSpeed(it)
                }
            } else {
                RxToast.warning(getString(R.string.no_get_information))
            }
        }
        /** 比赛结果 */
        mViewModel.raceResultResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            if (it != null) {
                refreshSortStateAndData(it)
            }
            mDatabind.swipeRecyclerView.scrollToPosition(0)
        }
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun refreshSortStateAndData(livePerformanceResponse: LivePerformanceResponse) {
        mDatabind.dataList = livePerformanceResponse
        mDatabind.tvHomingRate.text = livePerformanceResponse.bkPercent
        if (livePerformanceResponse.passResultBody.isEmpty()) {
            mDatabind.llEmptyDataLayout.isVisible = true
            mDatabind.swipeRecyclerView.isVisible = false
        } else {
            mDatabind.llEmptyDataLayout.isVisible = false
            mDatabind.swipeRecyclerView.isVisible = true
        }
        val totalPigeon = livePerformanceResponse.total
        mPageTotal = ceil(SettingUtil.div(totalPigeon.toDouble(), 50.00, 2)).toInt()//取整
        mDatabind.tvTotalPigeon.isGone = livePerformanceResponse.passResultBody == null || livePerformanceResponse.passResultBody.isEmpty()
        mDatabind.tvTotalPigeon.text =
            getString(R.string.tv_training_sign_pigeon_num) + totalPigeon + getString(R.string.yu) + ",  " + getString(R.string.altogether) + mPageTotal + getString(
                R.string.page
            )
        if (mIsPressedSort) {
            val drawableId: Int
            if (isReverse) {//升序(初始状态)
                mDatabind.tvAscendingOrder.text = getString(R.string.Ascending_order)
                drawableId = R.mipmap.icon_ascending_order_selected
            } else {//降序
                mDatabind.tvAscendingOrder.text = getString(R.string.Descending)
                drawableId = R.mipmap.icon_descending_order_unselected
            }
            isReverse = !isReverse
            mDatabind.ivAscendingOrder.setBackgroundResource(drawableId)
        }
        if (mPassType == 1) {
            mAdapter.setList(livePerformanceResponse.passResultBody)
            mAdapter.notifyDataSetChanged()
        } else {
            mAdapterXf.setList(livePerformanceResponse.passResultBody)
            mAdapterXf.notifyDataSetChanged()
        }
    }

    private fun getCalculateSpeed(it: RaceDetailInfoResponse) {
        currentStr = DatetimeUtil.getTimeString()
        curDate = DatetimeUtil.getCustomTime(currentStr)
        sunTimeList.clear()

        if (it.sun.isEmpty()) {
            mDatabind.tvSpeed.text = getString(R.string.time_out)
            LogUtils.warnInfo("日出日落时间为空")
            return
        }
        if (it.flyDis == "0.000000") {
            mDatabind.tvSpeed.text = getString(R.string.time_out)
            LogUtils.warnInfo("飞行空距为空")
            return
        }
        //循环读取日出日落时间并进行处理 +-30分钟
        it.sun.forEachIndexed { index, s ->
            if (index % 2 == 0) {//偶数
                DatetimeUtil.getOldAndNewTime(DatetimeUtil.getCustomTime(s), 30)?.let { it1 -> sunTimeList.add(it1) }
            } else {
                DatetimeUtil.getOldAndNewTime(DatetimeUtil.getCustomTime(s), -30)?.let { it1 -> sunTimeList.add(it1) }
            }
        }
        //新list中的0位置添加一条数据（司放时间）
        sunTimeList.add(0, it.flyTime)
        if (sunTimeList.isNotEmpty() && sunTimeList.size >= 2) {
            //判断当前是否在有效时间段内，若不在直接return,  (before:当前时间之前，after:当前时间之后)
            if (curDate.before(DatetimeUtil.getCustomTime(sunTimeList[0])) || curDate.after(
                    DatetimeUtil.getCustomTime(sunTimeList[sunTimeList.size - 1])
                )
            ) {
                mDatabind.tvSpeed.text = getString(R.string.time_out)
                return
            }
        }
        getTimeCost()
    }

    @SuppressLint("SetTextI18n")
    private fun getTimeCost() {
        nightHoursCount = 0
        //循环新list
        for (j in 0 until sunTimeList.size) {
            if (j == sunTimeList.size - 1) {//循环到列表的最后一条不再循环直接跳出
                mDatabind.tvSpeed.text = getString(R.string.time_out)
                return
            }
            if (j % 2 != 0) {//判断下标为偶数或者基数，偶数代表白天  基数代表晚上
                /** 得到两个时间之间的差（秒钟） */
                nightTimeCount = DatetimeUtil.getTimeDifferenceSecond(sunTimeList[j + 1], sunTimeList[j]).toInt()
                nightHoursCount += nightTimeCount
                mDatabind.tvSpeed.text = getString(R.string.time_out)
                continue
            } else {
                if (curDate.after(DatetimeUtil.getCustomTime(sunTimeList[j])) && curDate.before(
                        DatetimeUtil.getCustomTime(sunTimeList[j + 1])
                    )
                ) {
                    //循环执行代码块
                    CycleSender.INSTANCE.start({ _, _ ->
                        /**
                         * 1、执行周期循环的任务
                         * 2、循环获取最新的当前时间
                         * 3、计算分速
                         * 4、显示UI
                         * */
                        currentStr = DatetimeUtil.getTimeString()
                        //获取时间差总秒数
                        val second = DatetimeUtil.getTimeDifferenceSecond(currentStr, sunTimeList[0])
                        val countTime = (second - nightHoursCount).toDouble()//减去夜晚的时间
                        //如果当前时间在第一组日出日落时间范围内，当前时间-日出时间=飞行时间，参考空距/飞行时间 = 分速
                        val resultSpeed = SettingUtil.div(flyDistance * 1000, countTime, 5)
                        //当前时间-放飞时间-日落时间 = 飞行时间
                        val diffTime = DatetimeUtil.getTimeDifferenceMinute(currentStr, flyTime).toInt() //- nightTimeCount
                        val tString = Util.sub((diffTime * 60).toString(), nightTimeCount.toString())
                        val flyTimeResult = DatetimeUtil.convertMillisToHoursAndMinutes(tString.toLong() * 1000)
//                        LogUtils.debugInfo("jjj<->$diffTime<->$tString<->$flyTimeResult")
                        val result = DecimalFormat("#0.000")
                        MainScope().launch {
                            mDatabind.tvSpeed.text = result.format(resultSpeed * 60) + "米/分"
                        }
//                        LogUtils.debugInfo(resultSpeed.toString() + "米/分" + "<<----->>" + flyTimeResult)
                        //循环获取当前日期 转换为date类型  循环比较与list中的时间段，若超出当前范围则重新开始循环
                        if (DatetimeUtil.getCustomTime(currentStr).after(DatetimeUtil.getCustomTime(sunTimeList[sunTimeList.size - 1]))) {
                            CycleSender.INSTANCE.stop()
                            getTimeCost()
                        }
                    }, 2)//间隔2秒循环一次
                    return
                } else {
                    CycleSender.INSTANCE.stop()
                }
            }
        }
    }

    override fun onStop() {
        super.onStop()
        CycleSender.INSTANCE.stop()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        CycleSender.INSTANCE.stop()
    }

    companion object {
        fun newInstance(raceId: Int, passId: Int, title: String, passType: Int, passCreateType: Int): FragmentLivePerformance {
            val fragment = FragmentLivePerformance()
            val bundle = Bundle()
            bundle.putInt("raceId", raceId)
            bundle.putInt("passId", passId)
            bundle.putString("title", title)
            bundle.putInt("passType", passType)
            bundle.putInt("passCreateType", passCreateType)//2-科汇类型
            fragment.arguments = bundle
            return fragment
        }
    }
}